<template>
  <a-row type="flex" style="flex-flow: inherit;">
    <a-col :flex="toggle ? '240px' : '30px'" style="margin-right: 12px;background-color: #fff;">
      <organizationTree :rootOpened="true" :multi="false" @select="onTreeSelect" @ok="getTreeData" @toggleBool="toggleBool">
      </organizationTree>
      <!-- <groups-tree @tree="getTreeData" @selectedKeys="getSelectedKeys" /> -->
    </a-col>
    <a-col flex="auto">
      <a-card class="topBox" :bordered="false" style="margin-bottom: 10px">
        <!-- 查询区域 -->
        <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" @keyup.enter.native="onQuery">
          <a-row>
            <a-col :span="7">
              <a-form-model-item label="人员姓名">
                <a-input v-model="form.name"placeholder="请输入" ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="7">
              <a-form-model-item label="人员类型">
                <!-- <a-select v-model="form.personType" placeholder="请选择" allowClear style="width:100%;">
                  <a-select-option :value="1">社区康复</a-select-option>
                  <a-select-option :value="2">社区戒毒</a-select-option>
                </a-select> -->
                <j-dict-select-tag
                  v-model="form.sjskType"
                  dictCode="personTypeConsult"
                   placeholder="请选择"
                  style="min-width: 100px"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="7">
              <a-form-model-item label="预约时间">
                <!-- <a-date-picker v-model="form.appointmentStartTime" value-format="YYYY-MM-DD HH:mm:ss" style="width:47.5%;" placeholder="开始时间" /> -->
                <!-- <a-date-picker v-model="form.appointmentEndTime" value-format="YYYY-MM-DD HH:mm:ss" style="margin-left: 5%;width:47.5%;" placeholder="结束时间" /> -->
                <a-range-picker v-model="appointmentTimeValue" style="width:100%;" valueFormat="YYYY-MM-DD"
                  @change="onAppointmentTimeChange" />
              </a-form-model-item>
            </a-col>
            <a-col :span="3">
              <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0;text-align: right;">
                <a-button type="primary" @click="onQuery"> 查询 </a-button>
                <a-button style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
              </a-form-model-item>
            </a-col>
            <a-col :span="7">
              <a-form-model-item label="咨询时间">
                <!-- <a-date-picker v-model="form.consultStartTime" value-format="YYYY-MM-DD HH:mm:ss" style="width:47.5%;" placeholder="开始时间" /> -->
                <!-- <a-date-picker v-model="form.consultEndTime" value-format="YYYY-MM-DD HH:mm:ss" style="margin-left: 5%;width:47.5%;" placeholder="结束时间" /> -->
                <a-range-picker v-model="consultTimeValue" style="width:100%;" valueFormat="YYYY-MM-DD"
                  @change="onConsultChange" />
              </a-form-model-item>
            </a-col>
            <a-col :span="9">
              <a-form-model-item label="状态" :label-col="{span: 3}" :wrapper-col="{span: 21}">
                <a-radio-group v-model="form.status">
                      <a-radio :value="1">
                        待预约
                      </a-radio>
                      <a-radio :value="2">
                        待咨询
                      </a-radio>
                      <a-radio :value="3">
                        已咨询
                      </a-radio>
                      <a-radio :value="4">
                        已取消
                      </a-radio>
                    </a-radio-group>
              </a-form-model-item>
            </a-col>
            
          </a-row>
        </a-form-model>
      </a-card>
      <a-card :bordered="false">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <!-- <a-dropdown>
                <a-menu slot="overlay" @click="handleMenuClick">
                  <a-menu-item key="1"> 心询机构 </a-menu-item>
                  <a-menu-item key="2"> 吸毒人员 </a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px" type="primary"> 预约 <a-icon type="down" /> </a-button>
              </a-dropdown> -->
          <!-- <a-button type="primary" @click="onAppointment()">预约</a-button> -->
          <a-button @click="exportConsultList">导出</a-button>
        </div>
        <!-- 表格展示 -->
        <div class="table-page-content">
          <z-table ref="table" rowKey="id" :showAlert="false" :showSelection="true" :loading="loading"
            :columns="columns" :dataSource="pageData" @selectedRow="onSelectedRow" @change="onTableChange">
            <!--操作-->
            <template slot="action" slot-scope="text, record">
              <a-button @click="onAppointment(record)" type="link" style="padding: 0" v-if="record.status === 1">预约</a-button>
              <a-button @click="onAppointment(record)" type="link" style="padding: 0;" v-if="record.status === 2">改约</a-button>
              <a-button @click="onAppointment(record)" type="link" style="padding: 0" v-if="record.status === 3 || record.status === 4">再次预约</a-button>
              <a-divider type="vertical" />
              <template  v-if="record.status === 2 || record.status === 1">
                <a-button @click="onEnter(record)" type="link" style="padding: 0">谈话录入</a-button>
                <a-divider type="vertical" />
              </template>
              <a-button @click="onDetail(record)" type="link" style="padding: 0; color: #333">详情</a-button>
              <template  v-if="record.status === 1 || record.status === 2">
                <a-divider type="vertical" />
                <a-button @click="onCancelConsult(record)" type="link" style="padding: 0; color: #333" >取消</a-button>
              </template>
              <a-divider type="vertical" />
              <a-button @click="onHistory(record)" type="link" style="padding: 0; color: #333">历史记录</a-button>
            </template>
          </z-table>
        </div>
      </a-card>
    </a-col>
    
    <OrganizeModal ref="OrganizeModal"></OrganizeModal>
    <DetailDrawer ref="DetailDrawer"></DetailDrawer>
  </a-row>
</template>

<script>
import moment from 'moment'
import { legalAidConsultList, consultListExportXls, cancelConsult } from '@/api/sjsk/legalAid/consult/index'
import {
    pageNewMech
  } from '@/api/sjsk/legalAid/organize'
import OrganizeModal from '../modules/OrganizeModal.vue'
import { downLoadFileReader } from '@/utils/export-util/util'
// import * as peopleApi from '@/api/wxSmuggle/people.js'
import OrganizationTree from './components/organizationTree'
import DetailDrawer from './components/DetailDrawer.vue'
export default {
  components: {
    OrganizationTree,
    DetailDrawer,
    OrganizeModal,
    
  },
  data() {
    return {
      moment,
      appointmentTimeValue: [],
      consultTimeValue: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 17 },
      rangePickerTime: [],
      loading: false,
      visible: false,
      isDisabled: true,
      reloading: false,
      selectKeys: [],
      form: {
        
        
        cancel: '', //	否取消 0：是；1：否		false	
        consultStatus: '', //	咨询状态		false	
        createTime: '', //	申请时间		false	
        departmentId: '460000000000', //	行政区划		false	
        mechName: '', //	咨询机构		false	
        name: '', //
      },
      treeDatas: [],
      toggle: true,
      areaOptions: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 60,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` //序号分页后连续
        },
        
        {
          title: '咨询人',
          dataIndex: 'realName',
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '身份证号',
          dataIndex: 'identityCard',
          align: 'left',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '人员类型',
          dataIndex: 'sjskTypeName',
          align: 'center'
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '咨询主题',
          dataIndex: 'topical',
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          customRender: (text) => {
            let str = ''
            switch (text){
              case 1:
              str = '待预约'
                break;
              case 2:
              str = '待咨询'
                break;
              case 3:
              str = '已咨询'
                break;
              case 4:
              str = '已取消'
                break;
              default:
                break;
            }
            return <j-ellipsis value={str} length={14} />
          },
        },
        {
          title: '预约时间',
          align: 'center',
          customRender: (text) => {
            const start = text.startTime || ''
            const end = text.endTime || ''
            return <j-ellipsis value={start + ' - ' + end} length={14} />
            
          },
        },
        {
          title: '咨询时间',
          dataIndex: 'consultTime',
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text || ''} length={20} />
          },
        },
        {
          title: '操作',
          width: 240,
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {
        records: []
      },
    }
  },
  
  
  created() {
    console.log('created')
    this.onQuery()
  },
  methods: {
    onCancelConsult(item) {
      const { id, realName } = item
      this.$confirm({
        title: '确认提示',
        content: `是否确定取消${realName}的法律援助预约`,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          cancelConsult({id}).then(res => {
            const { success, message }  = res
            if(success) {
              this.$message.success('取消成功！')
              this.onQuery()
            } else {
              this.$message.error(message)
            }
          })
        }
      })
      
    },
    
    onAppointmentTimeChange(date) {
      this.$set(this.pageFilter, 'appointmentStartTime', date[0])
      this.$set(this.pageFilter, 'appointmentEndTime', date[1])
    },
    onConsultChange(date) {
      this.$set(this.pageFilter, 'consultStartTime', date[0])
      this.$set(this.pageFilter, 'consultEndTime', date[1])
    },
    
    
    
    
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.appointmentTimeValue = []
      this.consultTimeValue = []
      this.pageFilter = {
        appointmentStartTime: '',
        appointmentEndTime: '',
        appointEndTime: '', //	预约结束时间		false
        appointStartTime: '', //	预约开始时间		false	
        cancel: '', //	否取消 0：是；1：否		false	
        consultStatus: '', //	咨询状态		false	
        createTime: '', //	申请时间		false	
        departmentId: '460000000000', //	行政区划		false	
        mechName: '', //	咨询机构		false	
        name: '', //
      }
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTimeChange() {

    },
    onStatusChange() {

    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    onTreeSelect(item) {
      this.form.departmentId = item.code
      this.onQuery()
      console.log(item)
    },
    refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      this.loading = true
      legalAidConsultList(form)
        .then((res) => {
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.loading = false
            this.$refs.table.onClearRowKeys()
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    getSelectedKeys(keys) {
      console.log(keys)
      this.$set(this.form, 'labelId', keys.join(','))
      this.onQuery()
    },

    
    // 预约
    onAppointment(item) {
      this.$router.push({
        path: "/legalAid/consult/appointment",
        query: {
          id: item.id,
          personType: item.personType,
          personId: item.personId
        }
      })
    },
    onEdit(record) {
      this.$refs.LawyerModal.show(record.id)
    },
    onDelete(record) {

    },
    onEnter(query) {
      this.$router.push({
        path: "/legalAid/consult/consult-enter",
        query: {
          id: query.id,
          personType: query.personType
        }
      })
    },
    onHistory(record) {
      this.$router.push({
        path: "/legalAid/consult/history",
        query: {
          id: record.sjskPersonId,
          personType: record.personType,
        }
      })
    },
    onDetail(record) {
      this.$refs.DetailDrawer.show(record)
    },
    exportConsultList() {
      consultListExportXls({...this.form, ...this.pageFilter}).then(async res => {
        const fileName = '法律咨询列表.xls'
        console.log(res)
        await downLoadFileReader(res, fileName)
      })
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = true
      this.$nextTick(() => (this.reloading = false))
    },
    getTreeData(datas) {
      console.log(datas, id)
      console.log(id)
    },
    toggleBool(bool) {
      console.log(bool)
      this.toggle = bool
    }
  },
}
</script>
<style lang="less" scoped>
.topBox /deep/.ant-row {
  margin-bottom: 0;
}

/deep/.ant-col-7 {
  width: 28%;
}

/deep/.ant-col-4 {
  width: 16%;
}
</style>
